package main

import (
	"fmt"
	"go/ftp/api"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

func main() {
	// 通过gin实现一个ftp-web server
	router := gin.Default()
	router.LoadHTMLGlob("templates/**/*")
	router.MaxMultipartMemory = 8 << 20
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "upload/index.tmpl", gin.H{
			"title": "Main website",
		})
	})
	router.POST("/upload", func(c *gin.Context) {

		form, _ := c.MultipartForm()
		files := form.File["upload[]"]
		for _, file := range files {
			log.Println(file.Filename)
			//上传文件到指定目录
			c.SaveUploadedFile(file, "./upload/"+file.Filename)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded", len(files)))
	})
	router.GET("/download", func(c *gin.Context) {
		files, filePaths, filesMapsList, err := api.GetFiles("./upload")
		if err != nil {
			log.Println(err)
		}
		c.HTML(http.StatusOK, "download/index.tmpl", gin.H{
			"title":        "Main website",
			"files":        files,
			"filesPaths":   filePaths,
			"mapFilePaths": filesMapsList,
		})
	})
	router.POST("/download", func(c *gin.Context) {
		filePath := "go.mod"
		file, err := os.Open(filePath)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		defer file.Close()

		fileInfo, err := file.Stat()
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileInfo.Name()))
		c.Header("Content-Type", "application/octet-stream")
		c.Header("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
		c.Header("Last-Modified", fileInfo.ModTime().UTC().Format(http.TimeFormat))

		_, err = io.Copy(c.Writer, file)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
	})
	router.Run()
}
